package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.SystemDictionaryItem;
import cn.wolfcode.crm.query.PageResult;
import cn.wolfcode.crm.query.SystemDictionaryItemQueryObject;
import cn.wolfcode.crm.service.ISystemDictionaryItemService;
import cn.wolfcode.crm.service.ISystemDictionaryService;
import cn.wolfcode.crm.service.impl.SystemDictionaryItemServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

//类似之前的Servlet
//请求用户的请求和相应

@Controller//IOC注解，将Controller交给Spring容器管理
@RequestMapping("/systemDictionaryItem")
public class SystemDictionaryItemController {

    //自动去Spring容器中找到对应类型或者名称的对象并设置给当前字段
    @Autowired
    private ISystemDictionaryItemService service = new SystemDictionaryItemServiceImpl();

    @Autowired
    private ISystemDictionaryService systemDictionaryService;

    //处理查询的请求
    @RequestMapping("/list")
    public String list(Model model, @ModelAttribute("qo") SystemDictionaryItemQueryObject qo){

        //如果没有传递parentId,此时不要做查询
        if(qo.getParentId() !=null) {
            PageResult result = service.query(qo);
            //将查询到的部门共享给页面
            model.addAttribute("result",result);
        }


        //查询所有字典目录
        model.addAttribute("dics", systemDictionaryService.listAll());

        //指定页面跳转的视图
        return "systemDictionaryItem/list";
    }

    @RequestMapping("/delete")
    public String delete(Long id){
        //从数据库中将对应id的部门删除
        service.delete(id);
        //重新访问list方法执行查询并跳转到list.jsp页面
        //默认的跳转方式是请求转发
        //使用redirect:前缀修改跳转的方式为重定向
        return "redirect:/systemDictionaryItem/list.do";
    }

    @RequestMapping("/input")
    public String input(Long id,Long parentId, Model model){
        if(id !=null){
            SystemDictionaryItem item = service.get(id);
            model.addAttribute("entity", item);
        }

        //查询出当前所在的目录的信息
        model.addAttribute("dic",systemDictionaryService.get(parentId));
        //跳转到input.jsp页面
        return "systemDictionaryItem/input";
    }

    //执行保存或更新
    @RequestMapping("/saveOrUpdate")
    public String saveOrUpdate(SystemDictionaryItem item){
        if(item.getId() !=null){
            //更新
            service.update(item);
        }else{
            //保存
            service.save(item);
        }

        return "redirect:/systemDictionaryItem/list.do?parentId="+item.getParentId();
    }
}
